package user_api

import (
	"benkendSystem/api"
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

// GetUserByKeyword 关键字查询用户
func GetUserByKeyword(keyward string) *gorm.DB {
	tx := database.DB.Model(new(models.User)).Select("id,username,phone_number,realname,enable_flag,created_at,updated_at").Where("deleted_flag != 1")
	if keyward != "" {
		tx = tx.Where("username LIKE ?", "%"+keyward+"%")
	}
	return tx
}

// GetUserList 获取用户列表
func GetUserList(c *gin.Context) {
	in := &GetUserRequestList{api.NewQueryRequest()}
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": "500",
			"msg":  "系统错误",
		})
		return
	}
	var (
		cnt  int64
		list = make([]*GetUserListReply, 0)
	)
	err = GetUserByKeyword(in.Keyword).Count(&cnt).Offset((in.Page - 1) * in.Size).Limit(in.Size).Find(&list).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": "500",
			"msg":  "系统异常",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": "200",
		"msg":  "操作成功",
		"result": gin.H{
			"list": list,
			"cnt":  cnt,
		},
	})
}
